<?php

namespace App\Http\Controllers;
use App\Models\AuthRelation;
use App\Models\AuthRole;
use App\Models\AuthRule;
use App\Models\SysConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class AuthController extends Controller {

    //默认配置
    protected  static $config = [
        'auth_on' => 1, // 权限开关
        'auth_type' => 1, // 认证方式，1为实时认证；2为登录认证。
        'auth_group' => 'auth_group', // 用户组数据表名
        'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
        'auth_rule' => 'auth_rule', // 权限规则表
        'auth_user' => 'member', // 用户信息表
    ];
    // 过滤权限
    public static $super = [
        "Admin_security",
        "Admin_securityShow",
        "Admin_info",
        "Admin_infoShow",
        "Login_exitLogin",
        "Upload_upload",
        "Upload_uploadExcel",
        "Develop_makeName",
        "Area_province",
        "Area_city",
        "Area_area",
        "Index_code",
        "Index_codePay",
        "SysConfig_imgCreate",
        "SysConfig_imgSave",
        "SysConfig_imgEdit",
        "SysConfig_videoCreate",
        "SysConfig_videoSave",
        "SysConfig_videoEdit",
    ];

    public static $menus = [
        [
            'name'  => 'develop',
            'title' => '开发者工具',
            'child' => [
                [
                    'name'  => 'Tool_time',
                    'title' => '时间组件' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_group',
                    'title' => '组织关系图' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_uEditor',
                    'title' => 'UEditor' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_upload',
                    'title' => '多附件上传' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_one',
                    'title' => '单附件上传' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_video',
                    'title' => '视频上传' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_QrCode',
                    'title' => '二维码' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_PCC',
                    'title' => '省市县三级联动' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Tool_PCS',
                    'title' => '省市大学三级联动' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Develop_index',
                    'title' => '一键生成MVC' ,
                    "show"  => 1,
                ],
                [
                    'name'  => 'Develop_save',
                    'title' => '保存',
                    "show"  => 0,
                ]
            ]
        ]
    ];
    public static function show_menu()
    {
        $menus    = AuthRule::where("status",1)->orderBy("sort","desc")->get()->toArray();
        $menus    = self::generate_tree($menus);
        $menuHtml = '';
        foreach ($menus as $key => $menu) {
            if (self::validate_permission($menu['name'])) {
                $href = str_replace('_', '/', $menu['name']);
                $href = "/api/".$href;
                if (!key_exists('child', $menu)) {
                    $menuHtml .= "<li class=\"layui-nav-item\"><a href=\"{$href}\">{$menu['title']}</a></li>";
                } else {
                    $menuHtml .= "<li class=\"layui-nav-item\">";
                    $menuHtml .= "<a class=\"\" href=\"javascript:;\">{$menu['title']}</a>";
                    $menuHtml .= "<dl class=\"layui-nav-child\">";
                    foreach ($menu['child'] as $val) {
                        if (self::validate_permission($val['name'])) {
                            $href = str_replace('_', '/', $val['name']);
                            //$href = url("/api/".$href);
                            $href = "/api/".$href;
                            $menuHtml .= "<dd><a href=\"{$href}\">{$val['title']}</a></dd>";
                        }
                    }
                    $menuHtml .= "</dl>";
                    $menuHtml .= "</li>";
                }
            }
        }
        echo $menuHtml;
        //return $menuHtml;
    }
    /**
     * 无限极分类生成层级数组
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @return array
     */
    public static  function generate_tree($list, $pk = 'id', $pid = 'parent_id', $child = 'child')
    {
        $items = [];
        foreach ($list as $val) $items[$val[$pk]] = $val; //id值必须和它对应的键值一致
        foreach ($items as $item)
            $items[$item[$pid]][$child][$item[$pk]] = &$items[$item[$pk]];
        return isset($items[0][$child]) ? $items[0][$child] : [];
    }

    protected static  function validate_permission($ruleName)
    {
        //超级管理员无需验证

        $currentId = session("admin_user")["id"];
        $authAdmin = [1];
        if (in_array($currentId, $authAdmin)) return true;
        //无需走验证的页面
        $notCheck = [
            'Role_admin'         => '获取角色用户明细',
            'Admin_security'     => '修改密码',
            'Admin_info'         => '修改个人资料',
            'Backup_ajax_backup' => '数据库备份文件列表',
            'Develop_index'      => '生成MVC'
        ];
        if (key_exists($ruleName, $notCheck)) return true;
        $auth = new Auth();
        //不是超级管理员角色，需要走Auth验证
        if (!$auth->check($ruleName, $currentId)) {

            return false;
        }
        return true;
    }



    /**
     * 开发者菜单
     */
    public static  function develop_menu()
    {
        if(!empty(env("GUANXU_DEBUG"))) {
            $menus    = self::$menus;
            $menuHtml = '';
            if (!is_null($menus)) {
                foreach ($menus as $key => $menu) {

                    $href = str_replace('_', '/', $menu['name']);
                    $href = url($href);
                    if (!key_exists('child', $menu)) {
                        $menuHtml .= "<li class=\"layui-nav-item\"><a href=\"{$href}\">{$menu['title']}</a></li>";
                    } else {
                        $menuHtml .= "<li class=\"layui-nav-item\">";
                        $menuHtml .= "<a class=\"\" href=\"javascript:;\">{$menu['title']}</a>";
                        $menuHtml .= "<dl class=\"layui-nav-child\">";
                        foreach ($menu['child'] as $val) {
                            if(empty($val["show"])) continue;
                            $href = str_replace('_', '/', $val['name']);
                            //$href = url($href);
                            //$href = url("/api/".$href);
                            $href = "/api/".$href;
                            $menuHtml .= "<dd><a href=\"{$href}\">{$val['title']}</a></dd>";
                        }
                        $menuHtml .= "</dl>";
                        $menuHtml .= "</li>";
                    }
                }
            }
            $user = session("admin_user");
            if($user["id"] != 1)  $menuHtml = '';
            //return $menuHtml;
            echo $menuHtml;

        }

    }

}


class Auth
{
    /**
     * @var object 对象实例
     */
    protected static $instance;
    /**
     * 当前请求实例
     * @var Request
     */
    protected $request;

    //默认配置
    protected $config = [
        'auth_on' => 1, // 权限开关
        'auth_type' => 1, // 认证方式，1为实时认证；2为登录认证。
        'auth_group' => 'auth_group', // 用户组数据表名
        'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
        'auth_rule' => 'auth_rule', // 权限规则表
        'auth_user' => 'member', // 用户信息表
    ];

    /**
     * 类架构函数
     * Auth constructor.
     */
    public function __construct()
    {
        //可设置配置项 auth, 此配置项为数组。
        if ($auth = AuthController::$super) {
            $this->config = array_merge($this->config, $auth);
        }
        // 初始化request
        //$this->request = $request;
    }

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 检查权限
     * @param $name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param $uid  int           认证用户的id
     * @param int $type 认证类型
     * @param string $mode 执行check的模式
     * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
     * @return bool               通过验证返回true;失败返回false
     */
    public function check($name, $uid, $type = 1, $mode = 'url', $relation = 'or')
    {
        if (!$this->config['auth_on']) {
            return true;
        }
        // 获取用户需要验证的所有有效规则列表
        $authList = $this->getAuthList($uid, $type);
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = [$name];
            }
        }
        $list = []; //保存验证通过的规则名
        if ('url' == $mode) {
            $REQUEST = unserialize(strtolower(serialize(Input::input())));
        }
        foreach ($authList as $auth) {
            $query = preg_replace('/^.+\?/U', '', $auth);

            if ('url' == $mode && $query != $auth) {
                parse_str($query, $param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST, $param);
                $auth = preg_replace('/\?.*$/U', '', $auth);
                if (in_array($auth, $name) && $intersect == $param) {
                    //如果节点相符且url参数满足
                    $list[] = $auth;
                }
            } else {
                // var_dump($auth);
                // var_dump($name);

                if (in_array($auth, $name)) {
                    $list[] = $auth;
                }
            }
        }
        if ('or' == $relation && !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ('and' == $relation && empty($diff)) {
            return true;
        }

        return false;
    }

    /**
     * 根据用户id获取用户组,返回值为数组
     * @param  $uid int     用户id
     * @return array       用户所属的用户组 array(
     *     array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *     ...)
     */
    public function getGroups($uid)
    {
        static $groups = [];
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }
        // 转换表名
        //$auth_group_access = Loader::parseName($this->config['auth_group_access'], 1);
        //$auth_group = Loader::parseName($this->config['auth_group'], 1);
        /* $auth_group_access = $this->config['auth_group_access'];
         $auth_group = $this->config['auth_group'];*/
        // 执行查询
        /*  $user_groups = Db::view($auth_group_access, 'uid,group_id')
              ->view($auth_group, 'title,rules', "{$auth_group_access}.group_id={$auth_group}.id", 'LEFT')
              ->where("{$auth_group_access}.uid='{$uid}' and {$auth_group}.status='1'")
              ->select();*/
        $user_groups = AuthRelation::join("auth_roles","auth_roles.id","=","auth_relations.group_id")
            ->where("auth_relations.uid",$uid)
            ->where("auth_roles.status",1)
            ->get()->toArray();
        $groups[$uid] = $user_groups ?: [];
        return $groups[$uid];
    }

    /**
     * 获得权限列表
     * @param integer $uid 用户id
     * @param integer $type
     * @return array
     */
    protected function getAuthList($uid, $type)
    {
        static $_authList = []; //保存用户验证通过的权限列表
        $t = implode(',', (array)$type);
        if (isset($_authList[$uid . $t])) {
            return $_authList[$uid . $t];
        }
        if (2 == $this->config['auth_type'] && Session::has('_auth_list_' . $uid . $t)) {
            return Session::get('_auth_list_' . $uid . $t);
        }
        //读取用户所属用户组
        $groups = $this->getGroups($uid);
        $ids = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_authList[$uid . $t] = [];
            return [];
        }
        //读取用户组所有权限规则
        $rules = AuthRule::whereIn("id",$ids)->where("status",1)->get()->toArray();
        //$rules = Db::name($this->config['auth_rule'])->where($map)->field('condition,name')->select();
        //循环规则，判断结果。
        $authList = []; //
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) {
                //根据condition进行验证
                $user = $this->getUserInfo($uid); //获取用户信息,一维数组
                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                //dump($command); //debug
                @(eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid . $t] = $authList;
        if (2 == $this->config['auth_type']) {
            //规则列表结果保存到session
            Session::set('_auth_list_' . $uid . $t, $authList);
        }

        return array_unique($authList);
    }

    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    protected function getUserInfo($uid)
    {
        static $userinfo = [];

        $user = Db::name($this->config['auth_user']);
        // 获取用户表主键
        $_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
        if (!isset($userinfo[$uid])) {
            $userinfo[$uid] = $user->where($_pk, $uid)->find();
        }

        return $userinfo[$uid];
    }
}
